package com.wenjiang.controller;


import com.wenjiang.common.annotation.TokenUserId;
import com.wenjiang.common.constat.RedisKey;
import com.wenjiang.common.dto.EmailSendParam;
import com.wenjiang.common.lang.EmailMessage;
import com.wenjiang.common.lang.Result;
import com.wenjiang.util.EmailUtils;
import com.wenjiang.util.RedisUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.Email;

@RequestMapping("/mallEmail")
@RestController
public class MallEmailController {

    @Autowired
    EmailUtils emailUtils;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @RequestMapping("/sendRegisterCode/{email}")
    public Object RegisterCode(@PathVariable("email") @Email @Valid String email){

        EmailMessage emailMessage = new EmailMessage();
        //生成验证码
        emailMessage.setMessageCode(emailUtils.genercode());

        //存入redis  10分钟内有效
        redisUtils.set(RedisKey.registerCodeKey +email, emailMessage.getMessageCode(),600);

        // 投递消息对消息队列
        EmailSendParam sendParam = new EmailSendParam();
        sendParam.setContent(emailMessage);
        sendParam.setEmail(email);
        sendParam.setFileName("CodeEmail.ftl");
        sendParam.setTitle("注册验证码");

        rabbitTemplate.convertAndSend("emailQueue",sendParam);

//        emailUtils.SendEmail(emailMessage,"注册验证码","CodeEmail.ftl",email);

        return Result.succ("验证码已发送到邮箱，请注意查收");
    }


    @RequestMapping("/sendPasswordCode/{email}")
    public Object passwordCode(@TokenUserId Long userId, @PathVariable("email") @Email @Valid String email){

        EmailMessage emailMessage = new EmailMessage();
        //生成验证码
        emailMessage.setMessageCode(emailUtils.genercode());

        //存入redis  10分钟内有效
        redisUtils.set(RedisKey.updatePasswordKey+userId , emailMessage.getMessageCode(),600);

        emailUtils.SendEmail(emailMessage,"修改密码验证码","CodeEmail.ftl",email);

        return Result.succ("验证码已发送到邮箱，请注意查收");
    }


}
